<template>
    <div class="star">
      <span v-for="(itemClass,index) in itemClasses" :class="itemClass" class="star-item" :style="starSize" track-by="index"></span><!--性能优化 track-by 数据不改变时不会重新渲染-->
    </div>
</template>

<script>
    export default {
      props:{
        score:{
          type: Number,
          required: true
        },
        size:{
          type: Number,
          default: 20
        },
        height: {
          type: Number,
          default: -1
        },
        marginRight: {
          type: Number,
          default: 20
        }
      },
      computed:{ //计算属性
        itemClasses(){
             let result = [];
             let score = Math.floor(this.score * 2 ) / 2;
             let hasDecimal = score % 1 !== 0;
             let integer = Math.floor(score);
             for(let i=0;i<integer;i++){
                   result.push("on");
             }
             if(hasDecimal){
                   result.push("half");
             }
             while(result.length < 5){
                  result.push("off");
             }
            return result;
         },
        starSize(){
          return {
            width: `${this.size}px`,
            height: `${this.height === -1 ? this.size : this.height}px`,
            'margin-right': `${this.marginRight}px`
          }
        }
      }
    }
</script>

<style scoped>
   .star{
         display: inline-block;
         font-size: 0;
         line-height: 0;
   }
   .star-item{
          display: inline-block;
          background-repeat: no-repeat;
          background-size: 100%;
          background-position: center;
    }
   .star-item.on{
          background-image: url(./images/on.png);
   }
   .star-item.half{
          background-image: url(./images/half.png);
   }
   .star-item.off{
          background-image: url(./images/off.png);
   }
</style>
